package com.studyroom.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.studyroom.entity.Announcement;
import com.studyroom.mapper.AnnouncementMapper;
import com.studyroom.service.AnnouncementService;
import com.studyroom.dto.SearchDTO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import com.studyroom.exception.ServiceException;

@Service
public class AnnouncementServiceImpl extends ServiceImpl<AnnouncementMapper, Announcement> implements AnnouncementService {

    @Autowired
    private AnnouncementMapper announcementMapper;

    @Override
    public List<Announcement> getPublishedAnnouncements() {
        LambdaQueryWrapper<Announcement> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Announcement::getStatus, 1)
               .orderByDesc(Announcement::getCreatedAt);
        return announcementMapper.selectList(wrapper);
    }
    
    @Override
    public Page<Announcement> getAnnouncementsByPage(int page, int size) {
        Page<Announcement> pageParam = new Page<>(page, size);
        LambdaQueryWrapper<Announcement> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Announcement::getStatus, 1)
               .orderByDesc(Announcement::getCreatedAt);
        return announcementMapper.selectPage(pageParam, wrapper);
    }
    
    @Override
    public Announcement getAnnouncementById(Long id) {
        return announcementMapper.selectById(id);
    }

    @Override
    public IPage<Announcement> search(SearchDTO params) {
        Page<Announcement> page = new Page<>(params.getCurrent(), params.getSize());
        
        // 手动处理日期时间参数
        LocalDateTime startDateTime = null;
        LocalDateTime endDateTime = null;
        
        try {
            if (params.getStartTime() != null && !params.getStartTime().isEmpty()) {
                startDateTime = LocalDateTime.parse(params.getStartTime(), 
                    DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
            }
            
            if (params.getEndTime() != null && !params.getEndTime().isEmpty()) {
                endDateTime = LocalDateTime.parse(params.getEndTime(), 
                    DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
            }
        } catch (Exception e) {
            throw new ServiceException("日期时间格式不正确: " + e.getMessage());
        }
        
        // 传递参数
        return baseMapper.searchAnnouncements(
            page, 
            params.getKeyword(), 
            params.getStatus(), 
            startDateTime, 
            endDateTime
        );
    }
} 